//
//  WKWatchViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/9/12.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKWatchViewController.h"
#import "WKWatchRecodeCell.h"
#import "WKFMDBTools.h"
#import "WKLoginHandel.h"
#import "WKEditorView.h"
#import "WKAlerView.h"
#import "WKHomeViewController.h"

@interface WKWatchViewController ()<UITableViewDelegate,UITableViewDataSource,WKEditorViewDelegate>

@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, strong) UITableView *mainTableView;

@property (nonatomic, strong) UIButton *btnRight;

@property (nonatomic, strong) WKEditorView *editorView;

@property (nonatomic, strong) WKAlerView *alertView;

@property (nonatomic, strong) YYLabel *footerLabel;

@property (nonatomic, strong) UIImageView *maskImgView;

@property (nonatomic, strong) WKFMDBTools *dbManger;

@property (nonatomic, strong) NSArray *dataList;

@property (nonatomic, strong) NSMutableArray *deleteArr;

@end

@implementation WKWatchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.deleteArr = [NSMutableArray array];

    self.automaticallyAdjustsScrollViewInsets = YES;
    
    [self loadData];
    
    [self setupUI];
}
- (void)loadData{
    
    self.dbManger = [WKFMDBTools defaultFMDBToos];
    self.dataList =[self.dbManger QueryWatchDataWithKey:kDBWatchTableName].mutableCopy;
    self.dataList = [[self.dataList reverseObjectEnumerator] allObjects];
}
- (void)setupUI{
    
    self.navgationBar.barTintColor = [UIColor whiteColor];
    self.statusbar.backgroundColor = RGBColor(40, 188, 203);
    [self middleTitleColor:[UIColor blackColor]];
    self.navItem.leftBarButtonItem = nil;
    [self setLeftButtonWithImage:@"icon_return" highlightedImage:@"icon_return" target:self action:@selector(backAction)];
    self.navItem.title = @"观看记录";
    [self.navgationBar addSubview:self.btnRight];
    
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kDeviceScreenWidth, 0.5)];
    self.lineView.backgroundColor = RGBColor(218, 218, 218);
    [self.view addSubview:self.lineView];

    self.mainTableView.editing = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64.5, kDeviceScreenWidth, kDeviceScreenHeight-95) style:UITableViewStylePlain];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.view addSubview:self.mainTableView];
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, 80)];
    self.footerLabel = [[YYLabel alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, 21)];
    self.footerLabel.center = footView.center;
    self.footerLabel.text = @"已加载全部内容";
    self.footerLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    self.footerLabel.textAlignment = NSTextAlignmentCenter;
    self.footerLabel.font = [UIFont systemFontOfSize:13];
    [footView addSubview:self.footerLabel];
    self.mainTableView.tableFooterView = footView;
    
    self.editorView = [[WKEditorView alloc]initWithFrame:CGRectMake(0, kDeviceScreenHeight, kDeviceScreenWidth, 70)];
    self.editorView.backgroundColor = RGBColor(245, 245, 245);
    self.editorView.delegate = self;
    [self.view addSubview:self.editorView];

    self.maskImgView = [[UIImageView alloc]initWithFrame:CGRectMake((kDeviceScreenWidth - 115)*0.5, (kDeviceScreenHeight - 120)*0.5, 115, 120)];
    self.maskImgView.image = [UIImage imageNamed:@"icon_watchrecode"];
    self.maskImgView.hidden = YES;
    [self.view addSubview:self.maskImgView];
    [self.mainTableView registerClass:[WKWatchRecodeCell class] forCellReuseIdentifier:@"watchCell"];
    
    if (self.dataList.count == 0) {
        //加占位图
        self.maskImgView.hidden = NO;
        self.footerLabel.hidden = YES;
    }else{
        self.maskImgView.hidden = YES;
        self.footerLabel.hidden = NO;
    }
}
- (void)backAction{
    if (self.block) {
        self.block();
    }
    [super backAction];
    
}
#pragma mark - 编辑
- (void)rightBtnAction:(UIButton*)sender{
    
    self.mainTableView.allowsMultipleSelectionDuringEditing = YES;
    self.mainTableView.editing = !self.mainTableView.editing;
    
    if (self.mainTableView.editing){
        [self.btnRight setTitle:@"取消" forState:UIControlStateNormal];
        [self.btnRight setImage:nil forState:UIControlStateNormal];
        if (self.deleteArr.count != 0) {
            [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除(%ld)",self.deleteArr.count] forState:UIControlStateNormal];
        }else{
            [self.editorView.btnDelete setTitle:@"删除" forState:UIControlStateNormal];
        }
        [self showEditorView];
        
    }else{
        [_btnRight setImage:IMG(@"icon_edtiorImg") forState:UIControlStateNormal];
        [self.btnRight setTitle:nil forState:UIControlStateNormal];
        self.editorView.btnSelectAll.selected = NO;
        [self.deleteArr removeObjectsInArray:self.dataList];
        [self.editorView.btnDelete setTitle:@"删除" forState:UIControlStateNormal];
        NSLog(@"单选：%ld",self.deleteArr.count);
        [self dismissEditorView];
    }
}
#pragma mark - 全选
- (void)WKEditorView:(WKEditorView *)wkEditorView btnSelectAllAction:(UIButton *)sender{
    
    sender.selected =! sender.selected;
    if (sender.selected) {
         [self.deleteArr removeObjectsInArray:self.dataList];
        [sender setTitle:@"取消全选" forState:UIControlStateSelected];
        for (int i = 0; i < self.dataList.count; i ++) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [self.mainTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        }
        NSLog(@"全选===：%ld",self.deleteArr.count);
        [self.deleteArr removeAllObjects];
        [self.deleteArr addObjectsFromArray:self.dataList];
        if (self.deleteArr.count != 0) {
            [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除(%ld)",self.deleteArr.count] forState:UIControlStateNormal];
        }
        NSLog(@"全选：%ld",self.deleteArr.count);
        
    }else{
        //取消全选
        [sender setTitle:@"全选" forState:UIControlStateNormal];
        [self dismissEditorView];
        self.mainTableView.editing = NO;
        [_btnRight setImage:IMG(@"icon_edtiorImg") forState:UIControlStateNormal];
        [self.btnRight setTitle:nil forState:UIControlStateNormal];
        [self.deleteArr removeObjectsInArray:self.dataList];
        NSLog(@"全选：%ld",self.deleteArr.count);
    }
}
#pragma mark - 删除
- (void)WKEditorView:(WKEditorView *)wkEditorView btnDeleteAction:(UIButton *)sender{
    if (self.deleteArr.count == 0 && self.dataList.count == 0) {
        [self showCustomAlertMessage:@"请选择条目!"];
        return;
    }else if (self.deleteArr.count == 0){
        [self showCustomAlertMessage:@"请选择要删除的内容!"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    //弹框
    self.alertView = [[WKAlerView alloc]initWithFrame:[UIScreen mainScreen].bounds message:@"确定要删除这些数据？" tip:nil title1:@"确定" title2:@"取消"];
    self.alertView.confirmBlock = ^{
        //执行删除操作
        [weakSelf deleWatchData];
        [weakSelf.alertView removeFromSuperview];
        
    };
    self.alertView.cancelBlock = ^{
        [weakSelf cancelDelegateWatchData];
    };
    self.alertView.deleteBlock = ^{
       [weakSelf cancelDelegateWatchData];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.alertView];
    
    [self dismissEditorView];
}
#pragma mark - 删除观看数据
- (void)deleWatchData{
    
    NSLog(@"-----%@",self.deleteArr);
    
    for (NSInteger i = 0; i<self.deleteArr.count; i++) {
        WKWatchModel *model = self.deleteArr[i];
        NSLog(@"要删除的观看数据:%@",model.section_name);
        [self.dbManger delegateWatchVideoWithTableName:kDBWatchTableName section_videoid:model.section_videoid];
        
        //[self.deleteArr removeObject:model];
    }
    [self.deleteArr removeAllObjects];
    self.mainTableView.editing = NO;
    [_btnRight setImage:IMG(@"icon_edtiorImg") forState:UIControlStateNormal];
    [self.btnRight setTitle:nil forState:UIControlStateNormal];
    self.editorView.btnSelectAll.selected = NO;
    [self dismissEditorView];
    self.dataList =[self.dbManger QueryWatchDataWithKey:kDBWatchTableName].mutableCopy;
    [self.mainTableView reloadData];
    if (self.deleteArr.count != 0) {
        [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除(%ld)",self.deleteArr.count] forState:UIControlStateNormal];
    }else{
        [self.editorView.btnDelete setTitle:@"删除" forState:UIControlStateNormal];
    }
    if (self.dataList.count == 0) {
        //加占位图
        self.maskImgView.hidden = NO;
        self.footerLabel.hidden = YES;
    }else{
        self.maskImgView.hidden = YES;
        self.footerLabel.hidden = NO;
    }
}
- (void)cancelDelegateWatchData{
    
    self.mainTableView.editing = NO;
    [self.btnRight setImage:IMG(@"icon_edtiorImg") forState:UIControlStateNormal];
    [self.btnRight setTitle:nil forState:UIControlStateNormal];
    self.editorView.btnSelectAll.selected = NO;
    [self dismissEditorView];
    [self.editorView.btnDelete setTitle:@"删除" forState:UIControlStateNormal];
    [self.deleteArr removeAllObjects];
    [self.alertView removeFromSuperview];
}
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"watchCell";
    WKWatchRecodeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[WKWatchRecodeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectedBackgroundView = [[UIView alloc]init];
    cell.tintColor = [UIColor lightGrayColor];// 改变编辑状态左侧勾选颜色
    cell.model = self.dataList[indexPath.row];
    
        return cell;
}
#pragma mark - tableView代理方法
//是否可以编辑  默认的时YES
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//选择编辑的方式,按照选择的方式对表进行处理
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
    
}
//选择你要对表进行处理的方式  默认是删除方式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

//选中时将选中行的在self.dataArray 中的数据添加到删除数组self.deleteArr中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
__weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    if (tableView.editing) {
        //数据处理
         [self.deleteArr addObject:[self.dataList objectAtIndex:indexPath.row]];
        for (NSInteger i = 0; i<self.deleteArr.count; i++) {
            WKWatchModel *model = self.deleteArr[i];
             NSLog(@"选中的观看视频1：%@",model.section_name);
        }
        NSLog(@"-----------------%ld",self.deleteArr.count);
         if (self.deleteArr.count != 0) {
         [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除(%ld)",self.deleteArr.count] forState:UIControlStateNormal];
         }else{
             [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除"] forState:UIControlStateNormal];
         }
         
        //[self showCustomAlertMessage:@"点击播放"];
        
        NSLog(@"单选：%ld",self.deleteArr.count);
    }else{
        //播放处理
        WKWatchRecodeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.model = self.dataList[indexPath.row];
        NSString *urlStr = [NSString stringWithFormat:@"%@/andriodwk/course/courseid/%@/userid/%@",kTestMainUrl,cell.model.courseid,userid];
        NSLog(@"单个课程地址：%@",urlStr);
        WKHomeViewController *homeVC = [[WKHomeViewController alloc]init];
        homeVC.isCollection = YES;
        homeVC.collectionBlock = ^{
            
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
            weakSelf.dataList =[weakSelf.dbManger QueryWatchDataWithKey:kDBWatchTableName].mutableCopy;
            weakSelf.dataList = [[weakSelf.dataList reverseObjectEnumerator] allObjects];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.mainTableView reloadData];
            });
        };
        homeVC.urlStr = urlStr;
        homeVC.userId = userid;
        [self.navigationController pushViewController:homeVC animated:YES];
    }
    
}
//取消选中时 将存放在self.deleteArr中的数据移除
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath  {
    
    if (tableView.editing) {
         [self.deleteArr removeObject:[self.dataList objectAtIndex:indexPath.row]];
        for (NSInteger i = 0; i<self.deleteArr.count; i++) {
            WKWatchModel *model = self.deleteArr[i];
            NSLog(@"选中的观看视频2：%@",model.section_name);
        }
         if (self.deleteArr.count != 0) {
         [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除(%ld)",self.deleteArr.count] forState:UIControlStateNormal];
         }else{
         [self.editorView.btnDelete setTitle:[NSString stringWithFormat:@"删除"] forState:UIControlStateNormal];
         }
                NSLog(@"单选：%ld",self.deleteArr.count);
    }else{
        
        //[self showCustomAlertMessage:@"点击播放"];
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 120;
}
- (void)showEditorView{
    
    [UIView animateWithDuration:0.2 animations:^{
        self.editorView.frame = CGRectMake(0, kDeviceScreenHeight - 70, kDeviceScreenWidth, 70);
    }];
    
    
}
- (void)dismissEditorView{
    
    [UIView animateWithDuration:0.2 animations:^{
        self.editorView.frame = CGRectMake(0, kDeviceScreenHeight, kDeviceScreenWidth, 70);
    }];
}
- (UIButton *)btnRight{
    
    if (_btnRight == nil) {
        _btnRight = [UIButton  buttonWithType:UIButtonTypeCustom];
        _btnRight.frame = CGRectMake(kDeviceScreenWidth - 40, (44-35)*0.5, 35,35);
        [_btnRight setImage:IMG(@"icon_edtiorImg") forState:UIControlStateNormal];
        [_btnRight setTitleColor:RGBColor(40, 188, 203) forState:UIControlStateNormal];
        _btnRight.titleLabel.font = [UIFont systemFontOfSize:15];
        [_btnRight addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnRight;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
